let mysql = require("mysql");
const LOCAL = {
  host: 'localhost',
  user: 'root',
}
const ONLINE = {
  host: "121.4.93.25",
  user: "mall",
}

let pool = mysql.createPool({
  connectionLimit: 10,
  password: "123456",
  database: "mall",
  multipleStatements: true,
  ...LOCAL
  // debug: true,
});
//常规SQL
let query = function (sql, arr = [], callback) {
  //建立链接
  pool.getConnection(function (err, connection) {
    if (err) throw err;
    console.log(sql, "sql语句", arr);
    connection.query(sql, arr, function (error, results, fields) {
      //将链接返回到连接池中，准备由其他人重复使用
      connection.release();
      if (error) throw error;
      //执行回调函数，将数据返回
      callback && callback(results);
    });
  });
};
//promise改写
const select = (sql, arr = []) => {
  return new Promise((resolve, reject) => {
    //建立链接
    pool.getConnection(function (err, connection) {
      if (err) throw err;
      console.log(sql, "sql语句", arr);
      connection.query(sql, arr, function (error, results, fields) {
        //将链接返回到连接池中，准备由其他人重复使用
        connection.release();
        if (error) throw error;
        //执行回调函数，将数据返回
        resolve(results)
      });
    });
  })
}
module.exports = {
  query,
  pool,
  select
};